package pers.qianyu.month_202011.date_20201115;

import pers.qianyu.util.*;

import java.util.*;

/**
 * 567. 字符串的排列
 * https://leetcode-cn.com/problems/permutation-in-string/
 *
 * @author mizzle rain
 * @date 2020-11-15 22:29
 */
public class CheckInclusion {
    /**
     * 使用模板
     */
    public boolean checkInclusion(String s1, String s2) {
        HashMap<Character, Integer> need = new HashMap<>();
        HashMap<Character, Integer> window = new HashMap<>();
        for (int i = 0; i < s1.length(); i++) {
            char c = s1.charAt(i);
            need.put(c, need.getOrDefault(c, 0) + 1);
        }
        int left = 0, right = 0;
        int valid = 0;
        while (right < s2.length()) {
            char c = s2.charAt(right);
            if (need.containsKey(c)) {
                window.put(c, window.getOrDefault(c, 0) + 1);
                if (window.get(c).equals(need.get(c))) {
                    valid++;
                }
            }
            right++;
            while ((right - left) >= s1.length()) {
                if (valid == need.size()) {
                    return true;
                }
                char c1 = s2.charAt(left);
                if (need.containsKey(c1)) {
                    if (window.get(c1).equals(need.get(c1))) {
                        valid--;
                    }
                    window.put(c1, window.get(c1) - 1);
                }
                left++;
            }
            ArrayUtil.printArr(s2.toCharArray(), left, right);
        }
        return false;
    }


    public static void main(String[] args) {
        ArrayUtil.printIndex("ooolleoooleh".length());
        CheckInclusion c = new CheckInclusion();
        //boolean result = c.checkInclusion("adc", "dcda");
        //boolean result = c.checkInclusion("ab", "eidbaooo");
        //boolean result = c.checkInclusion("adc", "dcda");
        boolean result = c.checkInclusion("hello", "ooolleoooleh");
        System.out.println("result = " + result);
    }
}
